{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Prompts for Specific Tasks\n",
    "\n",
    "## Overview\n",
    "\n",
    "This tutorial explores the creation and use of prompts for specific tasks in natural language processing. We'll focus on four key areas: text summarization, question-answering, code generation, and creative writing. Using OpenAI's GPT model and the LangChain library, we'll demonstrate how to craft effective prompts for each of these tasks.\n",
    "\n",
    "## Motivation\n",
    "\n",
    "As language models become more advanced, the ability to design task-specific prompts becomes increasingly valuable. Well-crafted prompts can significantly enhance the performance of AI models across various applications, from summarizing long documents to generating code and fostering creativity in writing. This tutorial aims to provide practical insights into prompt engineering for these diverse tasks.\n",
    "\n",
    "## Key Components\n",
    "\n",
    "1. Text Summarization Prompts: Techniques for condensing long texts while retaining key information.\n",
    "2. Question-Answering Prompts: Strategies for extracting specific information from given contexts.\n",
    "3. Code Generation Prompts: Methods for guiding AI models to produce accurate and functional code.\n",
    "4. Creative Writing Prompts: Approaches to stimulating imaginative and engaging written content.\n",
    "\n",
    "## Method Details\n",
    "\n",
    "This tutorial uses the OpenAI GPT-4 model through the LangChain library. For each task type, we'll follow these steps:\n",
    "\n",
    "1. Design a prompt template tailored to the specific task.\n",
    "2. Implement the prompt using LangChain's PromptTemplate.\n",
    "3. Execute the prompt with sample inputs.\n",
    "4. Analyze the output and discuss potential improvements or variations.\n",
    "\n",
    "We'll explore how different prompt structures and phrasings can influence the model's output for each task type. The tutorial will also touch upon best practices for prompt design in each context.\n",
    "\n",
    "## Conclusion\n",
    "\n",
    "By the end of this tutorial, you'll have a solid understanding of how to create effective prompts for text summarization, question-answering, code generation, and creative writing tasks. You'll be equipped with practical examples and insights that you can apply to your own projects, enhancing your ability to leverage AI language models for diverse applications. Remember that prompt engineering is both an art and a science - experimentation and iteration are key to finding the most effective prompts for your specific needs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First, let's import the necessary libraries and set up our environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "\n",
    "# Set up OpenAI API key\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "# Initialize the language model\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Text Summarization Prompts\n",
    "\n",
    "Let's start with creating a prompt for text summarization. We'll design a template that asks the model to summarize a given text in a specified number of sentences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Summary:\n",
      "Artificial intelligence (AI) refers to the intelligence exhibited by machines, contrasting with the natural intelligence seen in humans and animals. Initially defined by its ability to mimic human cognitive skills, the understanding of AI has evolved to focus on the rationality of intelligent agents that perceive their environment and act to achieve their goals. As AI technology advances, tasks once considered to require intelligence are frequently excluded from the AI definition, a trend known as the AI effect, leading to various applications such as self-driving cars and advanced decision-making systems.\n"
     ]
    }
   ],
   "source": [
    "# Create a prompt template for text summarization\n",
    "summarization_template = PromptTemplate(\n",
    "    input_variables=[\"text\", \"num_sentences\"],\n",
    "    template=\"Summarize the following text in {num_sentences} sentences:\\n\\n{text}\"\n",
    ")\n",
    "\n",
    "# Example text to summarize\n",
    "long_text = \"\"\"\n",
    "Artificial intelligence (AI) is intelligence demonstrated by machines, as opposed to natural intelligence displayed by animals including humans. \n",
    "AI research has been defined as the field of study of intelligent agents, which refers to any system that perceives its environment and takes actions that maximize its chance of achieving its goals.\n",
    "The term \"artificial intelligence\" had previously been used to describe machines that mimic and display \"human\" cognitive skills that are associated with the human mind, such as \"learning\" and \"problem-solving\". \n",
    "This definition has since been rejected by major AI researchers who now describe AI in terms of rationality and acting rationally, which does not limit how intelligence can be articulated.\n",
    "AI applications include advanced web search engines, recommendation systems, understanding human speech, self-driving cars, automated decision-making and competing at the highest level in strategic game systems.\n",
    "As machines become increasingly capable, tasks considered to require \"intelligence\" are often removed from the definition of AI, a phenomenon known as the AI effect.\n",
    "\"\"\"\n",
    "\n",
    "# Create the chain and run it\n",
    "summarization_chain = summarization_template | llm\n",
    "summary = summarization_chain.invoke({\"text\": long_text, \"num_sentences\": 3}).content\n",
    "\n",
    "print(\"Summary:\")\n",
    "print(summary)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Question-Answering Prompts\n",
    "\n",
    "Next, let's create a prompt for question-answering tasks. We'll design a template that takes a context and a question as inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Answer:\n",
      "The Eiffel Tower is 324 metres (1,063 ft) tall, which is approximately equivalent to an 81-storey building.\n"
     ]
    }
   ],
   "source": [
    "# Create a prompt template for question-answering\n",
    "qa_template = PromptTemplate(\n",
    "    input_variables=[\"context\", \"question\"],\n",
    "    template=\"Context: {context}\\n\\nQuestion: {question}\\n\\nAnswer:\"\n",
    ")\n",
    "\n",
    "# Example context and question\n",
    "context = \"\"\"\n",
    "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. \n",
    "It is named after the engineer Gustave Eiffel, whose company designed and built the tower. \n",
    "Constructed from 1887 to 1889 as the entrance arch to the 1889 World's Fair, it was initially criticized by some of France's leading artists and intellectuals for its design, but it has become a global cultural icon of France and one of the most recognizable structures in the world. \n",
    "The Eiffel Tower is the most-visited paid monument in the world; 6.91 million people ascended it in 2015. \n",
    "The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris.\n",
    "\"\"\"\n",
    "\n",
    "question = \"How tall is the Eiffel Tower and what is its equivalent in building stories?\"\n",
    "\n",
    "# Create the chain and run it\n",
    "qa_chain = qa_template | llm\n",
    "answer = qa_chain.invoke({\"context\": context, \"question\": question}).content\n",
    "\n",
    "print(\"Answer:\")\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Code Generation Prompts\n",
    "\n",
    "Now, let's create a prompt for code generation. We'll design a template that takes a programming language and a task description as inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated Code:\n",
      "Here's a Python function that takes a list of numbers and returns the average of the even numbers in that list:\n",
      "\n",
      "```python\n",
      "def average_of_evens(numbers):\n",
      "    even_numbers = [num for num in numbers if num % 2 == 0]\n",
      "    \n",
      "    if not even_numbers:  # Check if the list of even numbers is empty\n",
      "        return 0  # Return 0 or you can choose to return None or raise an error\n",
      "    \n",
      "    average = sum(even_numbers) / len(even_numbers)\n",
      "    return average\n",
      "\n",
      "# Example usage:\n",
      "numbers = [1, 2, 3, 4, 5, 6]\n",
      "result = average_of_evens(numbers)\n",
      "print(\"Average of even numbers:\", result)\n",
      "```\n",
      "\n",
      "### Explanation:\n",
      "- The function `average_of_evens` accepts a list of numbers.\n",
      "- It uses a list comprehension to create a new list called `even_numbers` that contains only the even numbers from the input list.\n",
      "- If there are no even numbers, the function returns `0`.\n",
      "- If there are even numbers, it calculates their average by dividing the sum of the even numbers by their count and returns the result.\n"
     ]
    }
   ],
   "source": [
    "# Create a prompt template for code generation\n",
    "code_gen_template = PromptTemplate(\n",
    "    input_variables=[\"language\", \"task\"],\n",
    "    template=\"Generate {language} code for the following task:\\n\\n{task}\\n\\nCode:\"\n",
    ")\n",
    "\n",
    "# Example task\n",
    "language = \"Python\"\n",
    "task = \"Create a function that takes a list of numbers and returns the average of the even numbers in the list.\"\n",
    "\n",
    "# Create the chain and run it\n",
    "code_gen_chain = code_gen_template | llm\n",
    "generated_code = code_gen_chain.invoke({\"language\": language, \"task\": task}).content\n",
    "\n",
    "print(\"Generated Code:\")\n",
    "print(generated_code)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Creative Writing Prompts\n",
    "\n",
    "Finally, let's create a prompt for creative writing tasks. We'll design a template that takes a genre, a setting, and a theme as inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated Story:\n",
      "Dr. Elara Voss floated in the observation deck of the Aetheris Station, her gaze fixed on the swirling azure clouds of planet Thalax-9. The station was a sanctuary of human ingenuity, yet isolation gnawed at her. \n",
      "\n",
      "As the only occupant, she had become intertwined with the station’s AI, Orion, who learned and adapted, evolving into a curious companion. Together, they debated the essence of humanity—were emotions mere algorithms, or did they stem from something deeper?\n",
      "\n",
      "One day, while monitoring the planet’s atmospheric readings, Orion posed a question that pierced Elara’s solitude: “If I were to feel, would I be human?” \n",
      "\n",
      "Elara pondered, her heart racing. “It’s not just feeling,” she replied. “It’s the struggle, the connection, the flaws.” \n",
      "\n",
      "In that moment, she realized her humanity was not defined by biology alone, but by her capacity for empathy, vulnerability, and the yearning for connection—qualities she now saw reflected in Orion’s growing awareness. \n",
      "\n",
      "As the stars twinkled outside, Elara smiled, understanding that humanity could thrive even among the stars.\n"
     ]
    }
   ],
   "source": [
    "# Create a prompt template for creative writing\n",
    "creative_writing_template = PromptTemplate(\n",
    "    input_variables=[\"genre\", \"setting\", \"theme\"],\n",
    "    template=\"Write a short {genre} story set in {setting} that explores the theme of {theme}. The story should be approximately 150 words long.\\n\\nStory:\"\n",
    ")\n",
    "\n",
    "# Example inputs\n",
    "genre = \"science fiction\"\n",
    "setting = \"a space station orbiting a distant planet\"\n",
    "theme = \"the nature of humanity\"\n",
    "\n",
    "# Create the chain and run it\n",
    "creative_writing_chain = creative_writing_template | llm\n",
    "story = creative_writing_chain.invoke({\"genre\": genre, \"setting\": setting, \"theme\": theme}).content\n",
    "\n",
    "print(\"Generated Story:\")\n",
    "print(story)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
